package com.chats.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chats.mapper.MessageMapper;
import com.chats.mapper.UserMapper;
import com.chats.pojo.Message;
import com.chats.pojo.User;
import com.chats.pojo.vo.MessageVO;
import com.chats.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息服务实现类
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询两个用户的历史消息
     * @return
     */
    @Override
    public List<MessageVO> historyList(Long fromId, Long toId) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Message::getTime);
        if(toId == 0) {
            queryWrapper.eq(Message::getToId, toId);
        } else {
            queryWrapper.eq(Message::getFromId, fromId).eq(Message::getToId, toId)
                    .or()
                    .eq(Message::getFromId, toId).eq(Message::getToId, fromId);
        }
        List<Message> list = this.list(queryWrapper); // 所有消息列表
        List<MessageVO> messageVOList = new ArrayList<>();
        // 将Message类转换成MessageVO类
        for (Message message : list) {
            // 查询发送者用户信息
            User fromUser = userMapper.selectById(message.getFromId());
            MessageVO messageVO = new MessageVO(message, fromUser.getUsername());
            messageVOList.add(messageVO);
        }
        return messageVOList;
    }


}
